import React, { useState } from 'react';
import {
    FileOutlined,
    TeamOutlined,
    UserOutlined,
} from '@ant-design/icons';
import type { MenuProps } from 'antd';
import { Menu } from 'antd';
import { useNavigate, useLocation } from 'react-router-dom';

type MenuItem = Required<MenuProps>['items'][number];

function getItem(
    label: React.ReactNode,
    key: React.Key,
    icon?: React.ReactNode,
    children?: MenuItem[],
): MenuItem {
    return {
        key,
        icon,
        children,
        label,
    } as MenuItem;
}

const items: MenuItem[] = [
    // getItem('Page1', '/page1', <PieChartOutlined />),
    // getItem('Page2', '/page2', <DesktopOutlined />),
    getItem('User', 'sub1', <UserOutlined />, [
        getItem('Page3', '/sub1/page3'),
        getItem('Page4', '/sub1/page4'),
        getItem('Page5', '/sub1/page5'),
    ]),
    getItem('Team', 'sub2', <TeamOutlined />, [getItem('Page6', '/sub2/page6'), getItem('Page7', '/sub2/page7')]),
    getItem('Page8', '/page8', <FileOutlined />),
];

const MainMenu: React.FC = () => {

    // 点击导航栏跳转路由
    const navigateTo = useNavigate()
    const menuClick = (e: { key: string }) => {
        // 编程式导航
        navigateTo(e.key)
    }

    // 获取当前location的路由
    const currentRoute = useLocation()

    // 找到当前路由的父级的key并添加到openkeys当中
    function findTreeKeyByRoute(nodes: any, key: string) {
        // 判断nodes是否为null和undefinend
        if (nodes === null || nodes === undefined) {
            nodes = []
        }
        return nodes.map((item: { key: string; children: any[]; }) => {
            if (item.key === key) {
                return {
                    ...item,
                    children: findTreeKeyByRoute(item.children || [], key)
                }
            } else {
                // 如果节点的键与指定的键不匹配，则继续遍历子节点
                const filteredChildren = findTreeKeyByRoute(item.children || [], key)
                // filteredChildren非空， 表示子节点中有匹配的节点，则返回当前节点及其子节点
                if (filteredChildren.length > 0) {
                    return {
                        ...item,
                        children: filteredChildren,
                    }
                } else {
                    return undefined
                }
            }
        })
        .filter(Boolean)
    }

    // 获取当前路由的所有父节点key
    function findNodeKeys(data: any, result: string[] = []) {
        data.forEach((element: { key: string; children: string | any[]; }) => {
            result.push(element.key)
            if(element.children && element.children.length > 0) {
                findNodeKeys(element.children, result)
            }
        });
        return result
    }

    const treeNode = findTreeKeyByRoute(items, currentRoute.pathname)
    let nodekeys = findNodeKeys(treeNode)
    nodekeys.splice(nodekeys.length - 1, 1)

    // 当前展开的菜单项
    const [openKeys, setOpenKeys] = useState(nodekeys);
    // 展开节点的改变触发
    const switchOpenChange = (currentOpenKeys: string[]) => {
        if (openKeys.length === 0) {
            setOpenKeys(currentOpenKeys)
        } else {
            const subKey = currentOpenKeys[currentOpenKeys.length - 1]
            setOpenKeys([subKey])
        }
    }

    return (
        <Menu
            theme="dark"
            defaultSelectedKeys={[currentRoute.pathname]}
            openKeys={openKeys} mode="inline"
            items={items} onClick={menuClick}
            onOpenChange={switchOpenChange}
        />
    )
}

export default MainMenu